package com.ibm.cps.publisher;

import java.io.IOException;
import java.util.Arrays;

import org.apache.log4j.FileAppender;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.SimpleLayout;

import com.ibm.cps.message.MessageFields;
import com.ibm.cps.message.ParsedDataMessage;
import com.ibm.cps.newmessage.MetadataInputSchema;
import com.ibm.cps.newmessage.MetadataInputSchema.FieldType;
import com.ibm.datamodel.timeseries.SchemaFormat;
import com.ibm.factories.MessageParserFactory;
import com.ibm.interfaces.AbstractMessagePublisher;
import com.ibm.interfaces.IMessageParser;
import com.ibm.util.ErrorCode;
import com.ibm.util.JSONUtility;
import com.ibm.util.exception.CPSException;

public class LogPublisher extends AbstractMessagePublisher {
	private static Logger logger = Logger.getLogger(LogPublisher.class);
	private String logpath = new String();
	public LogPublisher(String metadata) throws CPSException {
		super(metadata);
		SimpleLayout layout = new SimpleLayout();
		String logPath = JSONUtility.getString(MessageFields.FIELNAME, metadata);
		this.logpath = logPath;
		try {
			FileAppender appender = new FileAppender(layout, logPath, false);
			logger.addAppender(appender);
		} catch (IOException e) {
			throw new CPSException(ErrorCode.INVALID_INPUT_ERROR, "can't create file appender " + logPath);
		}
		logger.setLevel((Level) Level.DEBUG);
	}

	@Override
	public void publishMessage(ParsedDataMessage parsedMessage, IMessageParser parser,  boolean isBuffer)
			throws CPSException {
		byte[] retMsg =  parser.restoreFromDataMessage(parsedMessage);
//		int i  = Integer.parseInt(new String(retMsg).split("\"b\":\"")[1].split(".0\",\"")[0]);
		logger.info("Alert: ");
//		logger.info(i);
		logger.info(new String("Logpath:"+logpath));
		logger.info(new String(retMsg));
	}

	@Override
	public MetadataInputSchema getInputSchema() {
		MetadataInputSchema schema = new MetadataInputSchema();
		schema.addField(FieldType.String, MessageFields.FIELNAME);
		return schema;
	}

	@Override
	public void close() {

	}

}
